require 'csv'

class CsvPresenterAction < WorkflowAction
  def valid_input_classes
    [ActiveRecord::Base]
  end

  def output_class
    String
  end

  def mime_type
    'text/csv'
  end
  
  def execute
    output = String.new
    CSV.generate_row(field_labels, field_labels.size, output)
    self.input.each do |record| 
      CSV.generate_row(data_row(record), field_names.size, output)
    end
    @output = output
  end
  
  def field_names
    self.quantities.blank? ? self.input.first.attributes.keys : self.quantities
  end

  def field_labels
    self.operands.blank? ? self.input.first.attributes.keys : self.operands
  end
  
  private
  
  def data_row(record)
    row = Array.new
    self.field_names.each { |field| row << record[field] }
    return row
  end
  
end
